package imu.g3.aspect;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


import imu.g3.model.LoginLogInfo;
import imu.g3.model.User;
import imu.g3.service.SystemLogService;
import imu.g3.util.IpAddressUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class SystemLogAspect {

    @Autowired
    SystemLogService service;

    /**
     * 登录成功方法的切入点
     */
    @Pointcut("execution(* imu.g3.service.*.loginSuccess(..))")
    public void loginSuccess(){
    }
    /**
     * 登录操作(后置通知)
     * @param joinPoint
     * @param object
     * @throws Throwable
     */
    @AfterReturning(value = "loginSuccess()", argNames = "joinPoint,object", returning = "object")
    public void loginLog(JoinPoint joinPoint, Object object) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UUID uuid = UUID.randomUUID();
        if(request.getSession().getAttribute("flag")=="loginsucc"){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            Object args[] = joinPoint.getArgs();
            User user = (User) request.getSession().getAttribute("User");
            LoginLogInfo loginlog=new LoginLogInfo();
            //获取登录日志
            loginlog.setUsername(user.getName());
            loginlog.setIntranetIP(IpAddressUtils.getIntranetIp(request));
            loginlog.setLoginTime(date);
            loginlog.setInternetIP(IpAddressUtils.getInternetIp(request));
            loginlog.setUuid(uuid.toString());
            loginlog.setHostName(IpAddressUtils.getHostName(request));
            //存储登录日志
            service.addLoginLog(loginlog);
        }

    }





}
